/**
 * 定义RemoteControlController远程控制
 */
(function(window, angular, undefined){

	var DataModificationController = angular.module('water.apps.sw.dataModification.dataModificationManager', ['ui.router','itfreer','waterCommon','RemoveControlService']);
	/**
	 * 数据修约控制器
	 */
	DataModificationController.controller('ModifyDataController',['$rootScope','$wdp','$httpData','$scope','$ReportService',
	                                                              'DateService','$waterDataCommon','$DataReportService','$formObject','$NavService',
	function($rootScope,$wdp,$httpData,$scope,$ReportService,DateService,$waterDataCommon,$DataReportService,$formObject,$NavService){

		if($rootScope.waterType == "1"){
			$scope.dataSourceSelect = [{"k":"3","v":"小时数据"},{"k":"6","v":"周期数据"},{"k":"4","v":"天数据"}];
			$scope.dataSource = "6"; //默认是小时数据
		}
		else{
			$scope.dataSourceSelect = [{"k":"3","v":"小时数据"},{"k":"4","v":"天数据"}];
			$scope.dataSource = "3"; //默认是小时数据
		}
		$httpData.HistoricalDataReportList = null;
		
		$scope.$on('dataPramChanged', function(event, data) {
			$scope.wwtpReportParm = data;
			$scope.getReport();
	    });
		
		$scope.dataFlagList = [{text:"手动监测",id:"mm"},
		                       {text:"正常测量",id:"N"},
		                       {text:"仪器故障",id:"D"},
		                       {text:"平行样",id:"ps"},
		                       {text:"加标回收",id:"ra"},
		                       {text:"校准",id:"cz"},
		                       {text:"标样核查",id:"sc"},
		                       {text:"水样不足",id:"Z"},
		                       {text:"采配水单元故障",id:"CPSDYGZ"},
		                       {text:"数采仪单元故障",id:"SCYDYGZ"},
		                       {text:"网络单元故障",id:"WLDYGZ"}];
		$scope.dataFlagTip = {};
		for(var i=0;i<$scope.dataFlagList.length;i++){
			var item = $scope.dataFlagList[i];
			$scope.dataFlagTip[item.id] = item.text;
		}
		
		/**
		 * 初始化查询条件
		 */
		function initQueryObj(){
			var nowDate = new Date();
			$scope.hourDate=nowDate.getFullYear()+"-"+(nowDate.getMonth()+1)+"-"+nowDate.getDate();
			
			$scope.yearlist=[];
			var currentYear=(new Date()).getFullYear();
			
			$scope.yearList = [];
			for(var i=0;i<4;i++){
				$scope.yearList.push({
					text:currentYear-i+"年",
					id:currentYear-i+""
				});
			}; 
			$scope.dayYear=currentYear+"";
			$scope.monthlist=[];
			for(var i=1;i<=12;i++){
				$scope.monthlist.push({
					text:i+"月",
					id:""+i
				});
			};
			$scope.dayMonth=((new Date()).getMonth() + 1)+"";
		}
		
		/**
		 * 锁定表头和时间列
		 */
		function tableScroll(){ 
			 angular.element("#dataTableContent").bind("scroll", function(e) {
				 var top=document.getElementById("dataTableContent").scrollTop; 
					var left=document.getElementById("dataTableContent").scrollLeft; 
					document.getElementById("datatimeCloumn").scrollTop=top; 
					document.getElementById("dataHeadContent").scrollLeft=left; 
			   })
		} 
		/**
		 * 获取结束日期
		 */
       function parseYearEndMonth(year, month){
			
			var end_day = new Date(year,month,0); 
			var endday = '' + end_day.getDate();
			
			if(endday.length==1){
				endday = '0' + endday;
			}
			var end_month = '' + month;
			if(end_month.length==1) {
				end_month = '0' + end_month;
			}
			
			var end_date = year + '-' + end_month + '-' + endday;
			return end_date+ " 23:59:59";
		}
		/**
		 * 历史信息获取数据
		 */
		$scope.getReport = function(){
			modifyArray=[];
			$scope.data = null;
			var queryObj = {};
			
			var stationId = $scope.wwtpReportParm.STATION_ID;
			var parmToChecksStr = $scope.wwtpReportParm.parmToChecksStr;
			var mn =$scope.wwtpReportParm.MN;
			if(mn == null){
				return ;
			}
			
			if(parmToChecksStr == ""){
				//$.messager.alert("提示","请选择要查看的参数!","info");
				return;
			}
			
			var parmToCheckList = $DataReportService.getParmCheckList($scope.wwtpReportParm.parmToCheckList,$scope.dataSource);
			$scope.parmToCheckList = parmToCheckList;
			$scope.parmToCharList = $scope.wwtpReportParm.parmToCheckList;
			
			switch($scope.dataSource){
				case '3':
				case '6':
					queryObj.START = $scope.hourDate + " 00:00:00";
					queryObj.END = $scope.hourDate + " 23:59:59";
					$scope.numLimit=13;
					break;
				case '4':
					var date = new Date();
					date.setFullYear($scope.dayYear);
					date.setMonth(parseInt($scope.dayMonth) - 1);
					date.setDate(1);
					date.setMonth(parseInt($scope.dayMonth));
					queryObj.START = $scope.dayYear+"-"+ $scope.dayMonth+"-01" + " 00:00:00";
					queryObj.END = parseYearEndMonth($scope.dayYear,$scope.dayMonth);
					$scope.numLimit=10;
					break;
			}
			
			queryObj.STATION_ID = stationId;
			queryObj.DATA_SOURCE = $scope.dataSource;
			queryObj.parmToChecks = parmToChecksStr;
			queryObj.mn = mn;
			queryObj.isForModify = "true";
			//获取历史数据
			$waterDataCommon.post("/DataReport/HistoricalData.do",queryObj,function(result){
				$scope.$apply(function(){
					$scope.data = result;
					$scope.limitList=$DataReportService.getParmLimit($scope.parmToCheckList,result.limitData);
				});
			});
		}
		
		$scope.showModifyWindow = function(data){
			if(data.FLAG != null && data.FLAG != ""){
				$scope.dataFlag = data.FLAG;
			}
			$scope.modifyData = angular.copy(data);
			$scope.oldData = angular.copy(data);
			$itfreer.openWindow('modifyData',{width:800,high:250});
		}
		//全选
		$scope.allCheck=function(){
			if ($("#allcheck").attr("checked")) {
				$(":checkbox").attr("checked", true);
				modifyArray=$scope.data.data;
			} else {
				$(":checkbox").attr("checked", false);
				modifyArray=[];
			}
		};
		
		$scope.modifySingle = function(data){
			$scope.itemCheck(data);
			$scope.modifyEvent();
		}
		
		//修改事件
		$scope.modifyEvent=function(){
			if(modifyArray.length>0){
				if(modifyArray.length==1){
					var data=modifyArray[0];
					$scope.modifyData = angular.copy(data);
					$scope.oldData = angular.copy(data);	
				}
				else{
					$scope.modifyData={};
					$scope.oldData={};
				}
				$itfreer.openWindow('modifyData',{width:800,high:250});
			}
			else{
				$.messager.alert("提示","请选择要修约数据","info");
			}
		};
		//存储修改数据数组
		var modifyArray=[];
		//勾选事件
		$scope.itemCheck=function(data){
			modifyArray=[];
			var isadd=false;
			if (modifyArray.length>0) {
				for(var i=0;i<modifyArray.length;i++){
					var obj=modifyArray[i];
					if(obj.QN){
						if(data.QN==obj.QN){
							modifyArray.splice(i,1);
							isadd=false;
							break;
						}
						else{
							isadd=true;
						}
					}
					else{
						isadd=true;
					}
				}
			}
			else{
				isadd=true;
			}
			if(isadd){
				modifyArray.push(data);
			}
		};
		
		/**
		 * 执行修约
		 */
		$scope.saveModifyData = function(data){
			var arr=Object.keys(data);
			if(arr.length>0){
			var newData = "";
			for(var i in $scope.parmToCheckList){
				var pollCode = $scope.parmToCheckList[i].parmName;
				var pollCodeOriginal = $scope.parmToCheckList[i].parmName_original;
				var attrName = $scope.parmToCheckList[i].attrName;
				
				if(attrName == null || attrName.indexOf("COU") > -1){
					continue;
				}
				
				var cou = data["P"+pollCode+"COU"];
				var avg = data["P"+pollCode+"AVG"];
				var flag = data["P"+pollCode+"FLAG"];
				newData +=" poll:"+pollCodeOriginal+",cou:"+cou+",avg:"+avg+",flag:"+flag
			}
			var qnStr="";
			var datatimeStr="";
			if(modifyArray.length>1){
				for(var j=0;j<modifyArray.length;j++){
					var obj=modifyArray[j];
					qnStr+=","+obj.QN;
					datatimeStr+=","+obj.TEMPDATE;
				}
				qnStr=qnStr.substring(1);
				datatimeStr=datatimeStr.substring(1);
			}
			else{
				var o=modifyArray[0];
				qnStr=o.QN;
				datatimeStr=o.TEMPDATE;
			}
			var modifyData = {
					mn:$scope.wwtpReportParm.MN,
					qn:qnStr,
					datatime:datatimeStr,
					userId:$formObject.user.userid,
					dataSource:$scope.dataSource,
					dataFlag:$scope.dataFlag,
					newData:newData,
					certificateId:data.MODIFY_CERTIFICATE_ID
			};
			
			$waterDataCommon.post("/DataModification/modifyData.do",modifyData,function(result){
				$.messager.alert("提示","修约成功","info");
				$scope.getReport();
				$itfreer.closeWindow('modifyData');
				$(":checkbox").attr("checked", false);
			});
		 }
			else{
				$.messager.alert("提示","没有选择要修约数据","info");
			}
		}
		
		/**
		 * 选择修约凭证
		 */
		$scope.selectCertificate = function(){
			$scope.queryCertificate();
			$itfreer.openWindow('selectCertificate');
		}
		
		/**
		 * 选定修约凭证
		 */
		$scope.chooseCertificate = function(certificateId){
			$scope.modifyData.MODIFY_CERTIFICATE_ID = certificateId;
			$itfreer.closeWindow('selectCertificate');
		}
		
		/**
		 * 查看凭证详情
		 */
		$scope.viewCertificate = function(id){
			$itfreer.openWindow('CertificateDetail',{width:800,high:250});
			$waterDataCommon.getPageRows("/DataModification/getCertificateInfo.do","CertificateInfo",{CERTIFICATE_ID:id},10,1,function(r){
				$scope.certificate = r;
			});
		}
		
		//修约凭证查询
		$scope.queryCertificate = function(){
			if($scope.queryCertObject){
				if(!($waterDataCommon.judgmentDate($scope.queryCertObject.startDate,$scope.queryCertObject.endDate))){
					$.messager.alert("提示","结束日期不能小于开始日期");
					return;
				}
			}
			var queryObj = {};
			if($scope.queryCertObject){
				queryObj.START = $scope.queryCertObject.startDate;
				queryObj.END = $scope.queryCertObject.endDate;
			}
			
			$waterDataCommon.getPageRows("/DataModification/getCertificateDataList.do","SelectCertDataList",queryObj,10,1,function(r){
				
			});
		};
		
		$ReportService.setSelectedTab("modify.data");	
		initQueryObj();
		tableScroll();
		if($wdp.stationListReady == "true"){
			$scope.$emit('askDataPramChange', $scope.reportParms); 
		}
	}]);
		
}(window, angular));